package com.guojing.jl.nio.bytebuff;

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 *  * ByteBuffer.allocate(16).getClass():
 *  *          class java.nio.HeapByteBuffer    - java 堆内存，读写效率较低，受到 GC 的影响
 *  *
 *  * ByteBuffer.allocateDirect(16).getClass():
 *  *          class java.nio.DirectByteBuffer  - 直接内存，读写效率高（少一次拷贝），不会受 GC 影响，分配的效率低
 *
 */
@Slf4j
public class Test1ByteBuffer {
    FileChannel channel = new FileInputStream("D:\\jl_project\\src\\springboot-learning\\netty-learning\\data.txt").getChannel();

    public Test1ByteBuffer() throws FileNotFoundException {
    }

    @Test
    public void test() {

        try {

            //缓冲区: 大小是5个字节
            ByteBuffer buffer = ByteBuffer.allocate(5);
            //从channel读取数据到buffer
            channel.read(buffer);
            //切换到读模式
            buffer.flip();
            while (buffer.hasRemaining()){

                //一次读取一个字节
                byte b = buffer.get();
                System.out.println((char)b);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Test
    public void readAll() {

        try {

            //缓冲区: 大小是5个字节
            ByteBuffer buffer = ByteBuffer.allocate(5);

            //切换到读模式
            buffer.flip();
            while (true){

                //从channel读取数据到buffer
                int length = channel.read(buffer);
                log.info("读取到的字节数:{}",length);
                if(length == -1){
                    break;
                }

                buffer.flip();
                while (buffer.hasRemaining()){
                    //一次读取一个字节
                    byte b = buffer.get();
                    log.info("内容: (char)b");
                }

                //切换为写模式
                buffer.clear();

            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
